import datetime
import json

from flask import Blueprint, render_template, request

from apps.util import mysql_do
from ext import socketio

user_bp = Blueprint('user', __name__, url_prefix='/user')

# 通信命名空间
name_spaceA = '/pageA'
name_spaceB = '/pageB'
name_spaceC = '/pageC'
name_spaceD = '/pageD'
# 公共变量
class_name = ''
should_num = ''
sick_num = ''
leader_name = ''
people_num = ''
status = ''
weather = ''

success_json = {'code': 200, 'data': 'success'}
faild_json = {'code': 500, 'data': 'Get request is not supported!'}


@user_bp.route('/pageA')
def pageA():
    class_msg = mysql_do.Select_class_index('A')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    print(class_msg)
    if class_msg != 0 and class_msg != None:
        return render_template('pageA.html', now_time=now_time, class_msg=class_msg)
    else:
        class_msg = [0, '无会议信息', '0', '0', '无', '无', '无', '0', '无', datetime.datetime(1995, 11, 11, 00, 00, 0)]
        return render_template('pageA.html', now_time=now_time, class_msg=class_msg)


@user_bp.route('/pageB')
def pageB():
    class_msg = mysql_do.Select_class_index('B')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    if class_msg != 0 and class_msg is not None:
        return render_template('pageB.html', now_time=now_time, class_msg=class_msg)
    else:
        class_msg = [0, '无会议信息', '0', '0', '无', '无', '无', '0', '无', datetime.datetime(1995, 11, 11, 00, 00, 0)]
        return render_template('pageB.html', now_time=now_time, class_msg=class_msg)


@user_bp.route('/pageB2')
def pageB2():
    class_msg = mysql_do.Select_class_index('B')
    contexts = mysql_do.Select_context('9')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    return render_template('pageB2.html', now_time=now_time, class_msg=class_msg, contexts=contexts)


@user_bp.route('/pageC')
def pageC():
    class_msg = mysql_do.Select_class_index('C')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    if class_msg != 0 and class_msg is not None:
        return render_template('pageC.html', now_time=now_time, class_msg=class_msg)
    else:
        class_msg = [0, '无会议信息', '0', '0', '无', '无', '无', '0', '无', datetime.datetime(1995, 11, 11, 00, 00, 0)]
        return render_template('pageC.html', now_time=now_time, class_msg=class_msg)


@user_bp.route('/pageD')
def pageD():
    class_msg = mysql_do.Select_class_index('D')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d')
    if class_msg != 0 and class_msg is not None:
        return render_template('pageD.html', now_time=now_time, class_msg=class_msg)
    else:
        class_msg = [0, '无会议信息', '0', '0', '无', '无', '无', '0', '无', datetime.datetime(1995, 11, 11, 00, 00, 0)]
        return render_template('pageD.html', now_time=now_time, class_msg=class_msg)


@user_bp.route('/class_insert', methods=['POST', 'GET'])
def class_insert():
    if request.method == 'POST':
        req_data = request.get_data().decode('utf-8')
        data = json.loads(req_data)
        class_name = data['class_name']
        should_num = data['should_num']
        sick_num = data['sick_num']
        leader_name = data['leader_name']
        status = data['status']
        weather = data['weather']
        meetid = data['meetid']
        place = data['place']
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if 'context' in data:
            context = data['context']
            class_id = mysql_do.Class_insert(class_name, should_num, sick_num, leader_name, status, weather, meetid,
                                             place,
                                             now_time)
            mysql_do.insert_context(meetid, context)
        else:
            class_id = mysql_do.Class_insert(class_name, should_num, sick_num, leader_name, status, weather, meetid,
                                             place,
                                             now_time)
        if class_id != 0:
            return success_json
        else:
            return 't_class插入失败'
    else:
        return faild_json


@user_bp.route('/people_insert1', methods=['POST', 'GET'])
def people_insert1():
    if request.method == 'POST':
        req_data = request.get_data().decode('utf-8')
        data = json.loads(req_data)
        global class_name, should_num, sick_num, leader_name, people_num, status, weather
        name = data['name']
        job = data['job']
        unit = ''
        group = ''
        pic_url = '未识别'
        people_code = data['people_code']
        site = data['site']
        id_card = data['id_card']
        meetName = data['meetName']
        event_name = 'pageA'
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 根据身份证号获取单位组别
        if len(id_card) > 0 and id_card != None:
            groups = mysql_do.Select_group(id_card, meetName)
            if groups != 'null' and groups != None:
                for group_line in groups:
                    group = group_line[0]
                    unit = group_line[1]
                    pic_url = group_line[2]
            else:
                group = '未识别'
                unit = '未识别'
        people_id = mysql_do.People_insert(name, job, unit, group, now_time, pic_url, people_code, site, id_card,
                                           meetName)
        if people_id != 0:
            t_class = mysql_do.Select_class(meetName)
            for class_line in t_class:
                class_name = class_line[1]
                should_num = str(class_line[2])
                sick_num = str(class_line[3])
                leader_name = class_line[4]
                status = class_line[5]
                weather = class_line[6]
            mysql_do.Relationship_insert(meetName, people_id)
            count_num = mysql_do.Count_num(meetName)
            for count_line in count_num:
                people_num = str(count_line)
            lose_num = int(should_num) - int(sick_num) - int(people_num)

            data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                    'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                    'sick_num': sick_num, 'lose_num': lose_num, 'people_num': people_num, 'leader_name': leader_name,
                    'status1': status, 'weather': weather
                    }
            if lose_num <= 0:
                data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                        'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                        'sick_num': sick_num, 'lose_num': '0', 'people_num': people_num, 'leader_name': leader_name,
                        'status1': status, 'weather': weather
                        }
            socketio.emit(event_name, data, broadcast=False, namespace=name_spaceA)
            return success_json
        else:
            return 't_people插入失败'
    else:
        return faild_json


@user_bp.route('/people_insert2', methods=['POST', 'GET'])
def people_insert2():
    if request.method == 'POST':
        req_data = request.get_data().decode('utf-8')
        data = json.loads(req_data)
        global class_name, should_num, sick_num, leader_name, people_num, status, weather
        name = data['name']
        job = data['job']
        unit = ''
        group = ''
        pic_url = '未识别'
        people_code = data['people_code']
        site = data['site']
        id_card = data['id_card']
        meetName = data['meetName']
        context_list = []
        event_name = 'pageB'
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 根据身份证号获取单位组别
        if len(id_card) > 0 and id_card != None:
            groups = mysql_do.Select_group(id_card, meetName)
            if groups != 'null' and groups != None:
                for group_line in groups:
                    group = group_line[0]
                    unit = group_line[1]
                    pic_url = group_line[2]
            else:
                group = '未识别'
                unit = '未识别'
        people_id = mysql_do.People_insert(name, job, unit, group, now_time, pic_url, people_code, site, id_card,
                                           meetName)
        contexts = mysql_do.Select_context(meetName)
        for context_line in contexts:
            context_list.append(context_line[0])
        print(str(context_list))
        if people_id != 0:
            t_class = mysql_do.Select_class(meetName)
            for class_line in t_class:
                class_name = class_line[1]
                should_num = str(class_line[2])
                sick_num = str(class_line[3])
                leader_name = class_line[4]
                status = class_line[5]
                weather = class_line[6]
            mysql_do.Relationship_insert(meetName, people_id)
            count_num = mysql_do.Count_num(meetName)
            for count_line in count_num:
                people_num = str(count_line)
            lose_num = int(should_num) - int(sick_num) - int(people_num)

            data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                    'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                    'sick_num': sick_num, 'lose_num': lose_num, 'people_num': people_num, 'leader_name': leader_name,
                    'status1': status, 'weather': weather, 'contexts': context_list
                    }
            if lose_num <= 0:
                data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                        'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                        'sick_num': sick_num, 'lose_num': '0', 'people_num': people_num, 'leader_name': leader_name,
                        'status1': status, 'weather': weather, 'contexts': context_list
                        }
            socketio.emit(event_name, data, broadcast=False, namespace=name_spaceB)
            print(data)
            return success_json
        else:
            return 't_people插入失败'
    else:
        return faild_json


@user_bp.route('/people_insert3', methods=['POST', 'GET'])
def people_insert3():
    if request.method == 'POST':
        req_data = request.get_data().decode('utf-8')
        data = json.loads(req_data)
        global class_name, should_num, sick_num, leader_name, people_num, status, weather
        name = data['name']
        job = data['job']
        unit = ''
        group = ''
        pic_url = '未识别'
        people_code = data['people_code']
        site = data['site']
        id_card = data['id_card']
        meetName = data['meetName']
        event_name = 'pageC'
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 根据身份证号获取单位组别
        if len(id_card) > 0 and id_card != None:
            groups = mysql_do.Select_group(id_card, meetName)
            if groups != 'null' and groups != None:
                for group_line in groups:
                    group = group_line[0]
                    unit = group_line[1]
                    pic_url = group_line[2]
            else:
                group = '未识别'
                unit = '未识别'
        people_id = mysql_do.People_insert(name, job, unit, group, now_time, pic_url, people_code, site, id_card,
                                           meetName)
        if people_id != 0:
            t_class = mysql_do.Select_class(meetName)
            for class_line in t_class:
                class_name = class_line[1]
                should_num = str(class_line[2])
                sick_num = str(class_line[3])
                leader_name = class_line[4]
                status = class_line[5]
                weather = class_line[6]
            mysql_do.Relationship_insert(meetName, people_id)
            count_num = mysql_do.Count_num(meetName)
            people_lists = mysql_do.Select_people_list(meetName)
            people_list = []
            for line in people_lists:
                dir = """{"name":""" + "\"" + line[0] + "\"" + """,""" + """"pic_url":""" + "\"" + line[
                    1] + "\"" + """}"""
                people_list.append(dir)
            for count_line in count_num:
                people_num = str(count_line)
            print("should_num:" + should_num + ",sick_num:" + sick_num + ",people_num:" + people_num)
            lose_num = int(should_num) - int(sick_num) - int(people_num)
            data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                    'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                    'sick_num': sick_num, 'lose_num': lose_num, 'people_num': people_num, 'leader_name': leader_name,
                    'status1': status, 'weather': weather, 'people_list': people_list
                    }
            if lose_num <= 0:
                data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                        'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                        'sick_num': sick_num, 'lose_num': '0', 'people_num': people_num, 'leader_name': leader_name,
                        'status1': status, 'weather': weather, 'people_list': people_list
                        }
            socketio.emit(event_name, data, broadcast=False, namespace=name_spaceC)
            return success_json
        else:
            return 't_people插入失败'
    else:
        return faild_json


@user_bp.route('/people_insert4', methods=['POST', 'GET'])
def people_insert4():
    if request.method == 'POST':
        req_data = request.get_data().decode('utf-8')
        data = json.loads(req_data)
        global class_name, should_num, sick_num, leader_name, people_num, status, weather
        name = data['name']
        job = data['job']
        unit = ''
        group = ''
        pic_url = '未识别'
        people_code = data['people_code']
        site = data['site']
        id_card = data['id_card']
        meetName = data['meetName']
        event_name = 'pageD'
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 根据身份证号获取单位组别
        if len(id_card) > 0 and id_card != None:
            groups = mysql_do.Select_group(id_card, meetName)
            if groups != 'null' and groups != None:
                for group_line in groups:
                    group = group_line[0]
                    unit = group_line[1]
                    pic_url = group_line[2]
            else:
                group = '未识别'
                unit = '未识别'
        people_id = mysql_do.People_insert(name, job, unit, group, now_time, pic_url, people_code, site, id_card,
                                           meetName)
        if people_id != 0:
            t_class = mysql_do.Select_class(meetName)
            for class_line in t_class:
                class_name = class_line[1]
                should_num = str(class_line[2])
                sick_num = str(class_line[3])
                leader_name = class_line[4]
                status = class_line[5]
                weather = class_line[6]
            mysql_do.Relationship_insert(meetName, people_id)
            count_num = mysql_do.Count_num(meetName)
            for count_line in count_num:
                people_num = str(count_line)
            lose_num = int(should_num) - int(sick_num) - int(people_num)

            data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                    'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                    'sick_num': sick_num, 'lose_num': lose_num, 'people_num': people_num, 'leader_name': leader_name,
                    'status1': status, 'weather': weather
                    }
            if lose_num <= 0:
                data = {'name': name, 'job': job, 'unit': unit, 'group': group, 'insert_time': str(now_time),
                        'pic_url': pic_url, 'class_name': class_name, 'should_num': should_num,
                        'sick_num': sick_num, 'lose_num': '0', 'people_num': people_num, 'leader_name': leader_name,
                        'status1': status, 'weather': weather
                        }
            socketio.emit(event_name, data, broadcast=False, namespace=name_spaceD)
            return success_json
        else:
            return 't_people插入失败'
    else:
        return faild_json
